package com.connector.server.handler;

import org.slf4j.LoggerFactory;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter
{
    private static final Logger log;
    private int loss_connect_time;
    
    public HeartBeatServerHandler() {
        this.loss_connect_time = 0;
    }
    
    public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            final IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state() == IdleState.READER_IDLE) {
                ++this.loss_connect_time;
                HeartBeatServerHandler.log.debug("30秒内没有检测到心跳,心跳次数:{}", (Object)this.loss_connect_time);
                if (this.loss_connect_time >= 3) {
                    HeartBeatServerHandler.log.debug("server main close channel");
                    ctx.channel().close();
                }
            }
        }
        else {
            this.loss_connect_time = 0;
            super.userEventTriggered(ctx, evt);
        }
    }
    
    public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
        HeartBeatServerHandler.log.debug("server channelRead..,,[{}]->Server :[{}]", (Object)ctx.channel().remoteAddress(), (Object)msg.toString());
    }
    
    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
    
    static {
        log = LoggerFactory.getLogger((Class)HeartBeatServerHandler.class);
    }
}
